#
# @lc app=leetcode.cn id=652 lang=python3
#
# [652] 寻找重复的子树
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
        nodes = dict()
        repeatNodes = set()

        def dfs(node: Optional[TreeNode]) -> str:
            if node is None:
                return ""
            serial = "".join([str(node.val), "(", dfs(node.left),
                              ")(", dfs(node.right), ")"])
            if (tree := nodes.get(serial)):
                repeatNodes.add(tree)
            else:
                nodes[serial] = node

            return serial

        dfs(root)

        return list(repeatNodes)
# @lc code=end
